package com.storlead.sjwt.security;

import com.storlead.sjwt.util.JwtTokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


/**
 * @Author: Timo
 * @Date: 2019/3/21 12:25
 * @Description: 授权拦截器
 */
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    private static Logger log = LoggerFactory.getLogger(JWTAuthorizationFilter.class);
    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        String requestUrl = request.getServletPath();

        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader,requestUrl));

        super.doFilterInternal(request, response, chain);
    }

    // 这里从token中获取用户信息并新建一个token
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader, String requestUrl) {
        String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        String username = JwtTokenUtils.getUsername(token);
        if (StringUtils.isEmpty(username)){
            throw new UsernameNotFoundException("请先登录");
        }
        String roleCode = JwtTokenUtils.getUserRole(token);
        if (username != null && hashRole(requestUrl,roleCode)){
            return new UsernamePasswordAuthenticationToken(username, null,
                    Collections.singleton(new SimpleGrantedAuthority(roleCode)));
        }
        return null;
    }

    private boolean hashRole(String requestUrl, String role){
        Map<String, List<String>> roleMap = new HashMap<>();
        roleMap.put("/tasks/test",Arrays.asList("ROLE_ADMIN","ROLE_USER","ROLE_ALL"));
        roleMap.put("/tasks/detail",Arrays.asList("ROLE_USER"));
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String key : roleMap.keySet()){
            log.info("{}<>{}",key,requestUrl);
            log.info("{}",antPathMatcher.match(key,requestUrl));
            if (antPathMatcher.match(key,requestUrl) && roleMap.get(key).contains(role)){
                return true;
            }
        }
        return false;
    }
}